// pages/board/board.js
var app = getApp(); //获取应用实例
Page({
  /**
   * 页面的初始数据
   */
  data: {
    limit: 10,
    records: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getLikeRank();
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  /**
   * 获取用户点赞列表
   */
  getLikeRank() {
    wx.showLoading({
      title: '',
    })
    const db = wx.cloud.database();
    const $ = db.command.aggregate;
    //查询点赞排行榜
    db.collection('likes').aggregate()
      .group({
        // 按纪念馆id字段分组
        _id: {
          id: '$id',
          name: '$name',
          iconPath: '$iconPath'
        },
        likes: $.sum('$like')
      })
      .sort({
        likes: -1,
      })
      .limit(10)
      .end()
      .then(res => {
        console.log(res.list)
        let records = [];
        res.list.forEach((elem, index) => {
          let item = {
            rank: index + 1,
            name: elem._id.name,
            iconPath: elem._id.iconPath,
            likes: elem.likes
          }
          records.push(item);
        });
        this.setData({
          records,
        });
        wx.hideLoading()
      }).catch((e) => {
        console.log(e)
        wx.hideLoading()
      })
  },
  //发送到朋友
  onShareAppMessage: function () {
    return {
      title: "中国革命纪念馆点赞排行榜",
      path: '/pages/board/board',
    }
  },
  //发送到朋友圈
  onShareTimeline() {
    return {
      title: "中国革命纪念馆点赞排行榜",
      imageUrl: '/statics/bg/share.png',
    }
  }
})